﻿using UnityEngine;
using System.Collections.Generic;

public class BlurBackGround : MonoBehaviour {

    public static RenderTexture targetTexture;
    public Camera blurCamera;
    public Camera uiCamera;

    public RenderTexture GetBlurBack()
    {
        List<Camera> cms = new List<Camera>(Camera.allCameras);
        cms.Sort(delegate (Camera a, Camera b) { return a.depth - b.depth > 0 ? -1 : 1; });
        for(int i = 0; i < cms.Count;++i)
        {
            if(cms[i] == uiCamera)
            {
                continue;
            }
            cms[i].targetTexture = targetTexture;
            cms[i].Render();
            cms[i].targetTexture = null;
        }
        blurCamera.Render();
        return targetTexture;
    }



    #region singleton
    private static BlurBackGround instance;
    public static BlurBackGround Instance
    {
        get
        {
            return instance;
        }
    }

    void Awake()
    {
        instance = this;
        int rtW = Screen.width / 4;
        int rtH = Screen.height / 4;
        targetTexture = RenderTexture.GetTemporary(rtW, rtH, 0);
        blurCamera.targetTexture = targetTexture;
    }
    void OnDestroy()
    {
        if (targetTexture != null)
        {
            targetTexture.Release();
            targetTexture = null;
        }
    }
    #endregion

}
